using System;
using System.Collections.Generic;
using System.Diagnostics;
using Mediasock.Client.Attribute;
using Mediasock.Client.Exception;
using Mediasock.Client.Service;
using Mediasock.Library.File;


namespace MSCF
{
    class Program
    {
        static void Main(string[] args)
        {
            //string serviceId = "com.webshots"; // requires no user-interaction
            string serviceId = "com.flickr"; // requires browser-authetnication

            // Creating the service manager instance
            ServiceManager serviceManager = new ServiceManager();

            // Getting the webshots service from the service manager
            // The service manager will call LoadService if the service is not loaded
            Service service = serviceManager.GetService(serviceId);
            Console.WriteLine(serviceId + " loaded");

            // Signin
            AttributesRecord signin = new AttributesRecord();
            signin["auth:user"] = "example"; // not required for browser-authentication
            signin["auth:pass"] = "example "; // not required for browser-authentication
            AttributesRecord response = service.SignIn(signin);

            // End if authentication failed
            if (response["status:code"] != "0")
            {
                printError(response);
                return;
            }

            // Check for authorization url
            if (response.Contains("auth:url"))
            {
                // Launch browser page for user to authenticate. Return if invalid
                response = authorizeUrl(service, response["auth:url"], response["auth:frob"]);
                if (response["status:code"] != "0")
                {
                    printError(response);
                    return;
                }
            }
            
            // Make a new taxon/photoset.
            AttributesCollection collection = service.MakeTaxa(new AttributesRecord("taxa:title", "MediaSock"));
           
            /*
            response = collection.Find(AttributesType.Sock)[0];

            if (response["status:code"] == "11")
                printError(response);
            else if (response["status:code"] != "0")
            {
                printError(response);
                return;
            }
            else
            {
                response = collection.Find(AttributesType.Taxa)[0];
                Console.WriteLine("Taxa created: " + response["taxa:id"]);
            }
            */
            // Get a list of albums
            collection = service.FindTaxa(new AttributesRecord());
            printCollection(collection, "Taxa");
            
            // If some taxa exist
            if (collection.Count > 0)
            {
                // Find the first non-empty taxa
                AttributesRecord taxa = new AttributesRecord();
                foreach (AttributesRecord record in collection.Find(AttributesType.Taxa))
                {
                    if (record["objects:count"] != "0")
                    {
                        taxa = record;
                        break;
                    }
                }
                
                // There are no non-empty taxa
                if (taxa.Count == 0)
                    return;

                
                // Upload a image to the first non-empty taxa
                AttributesRecord photo = new AttributesRecord();
                photo["file:original"] = "mediasock.jpg";
                photo["annotation:title"] = "MediaSock";
                photo["annotation:caption"] = "Test upload from MSCF";
                photo["taxa:id"] = taxa["taxa:id"];
                
                collection = service.SendObjects(new AttributesCollection(photo));
               
                printCollection(collection, "Uploaded objects");
               
                // Get the objects in the first non-empty taxa 

                collection = service.FindObjects(1, 20, taxa, 0);
                printCollection(collection, "Objects");

                
                // Download the first object from the first non-empty taxa
                // Add this attribute to cause download, optionally specify directory or full path as value to override default
                collection[0]["file:original"] = "";
                collection = service.ReceiveObjects(new AttributesCollection(collection[0]), @"C:\");
                printCollection(collection, "Downloaded objects");
            }
            
            // Done
            Console.WriteLine("Press any key to quit.");
            Console.ReadKey();
        }


        static void printError(AttributesRecord error)
        {
            Console.Write("Error #" + error["status:code"] + ": ");
            Console.WriteLine((error.Contains("status:message") ? error["status:message"] : "General Error"));
        }


        static void printCollection(AttributesCollection attributeCollection, string heading)
        {
            Console.WriteLine("---------------------------" + heading + "---------------------------");
            foreach (AttributesRecord record in attributeCollection)
            {
                // Don't print if method not supported
                if (record.Contains("status:code") && record["status:code"] == "11")
                {
                    Console.WriteLine(record["status:message"]);
                    return;
                }

                foreach (string key in record.Keys)
                    Console.WriteLine(key + " = " + record[key]);
            }
        }


        private static AttributesRecord authorizeUrl(Service service, string url, string frob)
        {
            Process.Start(url);
            Console.WriteLine("Press any key to complete authorization.");
            Console.ReadKey();

            AttributesRecord signin = new AttributesRecord();
            signin["auth:frob"] = frob;
            return service.SignIn(signin);
        }
    }
}